package hhm.android.base.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter

/**
 * A Group的类型
 * B Child的类型
 * T Group的ViewHolder
 * F Child的ViewHolder
 */
abstract class HBaseExpandableListAdapter<A, B, T, F>(
    var group: ArrayList<A>,
    var child: ArrayList<ArrayList<B>>,
    var groupLayout: Int,
    var childLayout: Int
) : BaseExpandableListAdapter() {
    override fun getGroupCount(): Int {
        return group.size
    }

    override fun getChildrenCount(groupPosition: Int): Int {
        return child[groupPosition].size
    }

    override fun getGroup(groupPosition: Int): A {
        return group[groupPosition]
    }

    override fun getChild(groupPosition: Int, childPosition: Int): B {
        return child[groupPosition][childPosition]
    }

    override fun getGroupId(groupPosition: Int): Long {
        return groupPosition.toLong()
    }

    override fun getChildId(groupPosition: Int, childPosition: Int): Long {
        return childPosition.toLong()
    }

    override fun hasStableIds(): Boolean {
        return true
    }

    override fun getGroupView(
        groupPosition: Int,
        isExpanded: Boolean,
        convertView: View?,
        parent: ViewGroup?
    ): View {
        val v: View
        val vh: T
        if (convertView == null) {
            v = LayoutInflater.from(parent?.context)
                .inflate(groupLayout, parent, false)
            vh = getGroupViewHolder(v)
        } else {
            v = convertView
            vh = v.tag as T
        }

        setGroupData(groupPosition, vh, group[groupPosition])

        v.tag = vh
        return v
    }

    override fun getChildView(
        groupPosition: Int,
        childPosition: Int,
        isLastChild: Boolean,
        convertView: View?,
        parent: ViewGroup?
    ): View {
        val v: View
        val vh: F
        if (convertView == null) {
            v = LayoutInflater.from(parent?.context)
                .inflate(childLayout, parent, false)
            vh = getChildViewHolder(v)
        } else {
            v = convertView
            vh = v.tag as F
        }

        setChildData(
            groupPosition,
            childPosition,
            isLastChild,
            vh,
            child[groupPosition][childPosition]
        )

        v.tag = vh
        return v
    }

    abstract fun getGroupViewHolder(v: View): T

    abstract fun getChildViewHolder(v: View): F

    abstract fun setGroupData(groupPosition: Int, vh: T, a: A)

    abstract fun setChildData(
        groupPosition: Int,
        childPosition: Int,
        isLastChild: Boolean,
        vh: F,
        b: B
    )

    abstract override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean
}